package com.zk.tools.schdule;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPStore;
import com.zk.tools.contants.Contants;
import com.zk.tools.util.MailSenderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import java.util.HashSet;
import java.util.Set;

@Component
public class HandleEmail {

    private static final Logger logger = LoggerFactory.getLogger(HandleEmail.class);

    private static Set<String> dateSet = new HashSet<>(Contants.COLLECTION_INIT_SIZE_64);

    private static int status = -1;

    @Scheduled(cron = Contants.HANDLEEMAIL_CRON)
    public void handle() {
        if (status == 1) {
            logger.error("正在处理邮件,此次定时操作跳过");
            return;
        }

        IMAPStore store = MailSenderUtil.getStoreIMAP();
        if (store == null) {
            return;
        }
        IMAPFolder folder = null;
        try {
            folder = (IMAPFolder) store.getFolder(Contants.EMAIL_FOLDER_INBOX);
            folder.open(Folder.READ_WRITE);
            Message[] msg = folder.getMessages();
//            int total = folder.getMessageCount();
            status = 1;
            handleIMAPMessage(msg);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                folder.close(true);
                store.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            status = 0;
        }
    }


    private void handleIMAPMessage(Message[] msg) throws MessagingException {
        for (Message msgInfo : msg) {
            IMAPMessage message = (IMAPMessage) (msgInfo);
            String dateKey = message.getSentDate() + "" + message.getReceivedDate();
            if (dateSet.add(dateKey)) {//防止重复操作同一份邮件
                String subject = message.getSubject();
                MailSenderUtil.handleSubJect(subject);
                message.setFlag(Flags.Flag.DELETED, true);
                message.saveChanges();
                logger.info("处理完成，邮件{}删除!", subject);
            }
        }
    }

}
